/*
全局资源管理模块
当前获得全局资源的线程下次将会最后判断，以保证各线程的稳定执行
*/

#include "mc31xx_hal_manager.h"
#include "mc3172.h"

ManagerCB_S g_stManager = {0};
ThreadCB_S g_stAllThread[64] = {0};

//线程控制块初始化
void HAL_Thread_Init(void)
{
    u8 i;
    HAL_ListInit((HAL_DL_LIST*)&g_stManager.list_mux);
    for (i = 0; i < 64; i++) {
        g_stAllThread[i].id=i;
        HAL_ListInit((HAL_DL_LIST*) & g_stAllThread[i].list_mux);
        HAL_ListTailInsert(&g_stManager.list_mux, &g_stAllThread[i].list_mux_manager);//全部挂入互斥锁管理表
    }
}

//资源管理线程独立运行
void HAL_MANAGER_MAIN(void)
{
    HAL_SYS_Init();
    ThreadCB_S *item,*next;
    while (1) {
        if (g_stManager.busy_mux == 1) {                                //资源已被占用
            assert_param(g_stManager.owner_mux);
            if (g_stManager.owner_mux->lock_mux == 0) {                 //未使用完毕，跳出
                assert_param(g_stManager.owner_mux->allow_mux == 1);
                HAL_ListTailInsert(&g_stManager.list_mux, &g_stManager.owner_mux->list_mux_manager);
                g_stManager.owner_mux->allow_mux = 0;                   //使用完毕，释放资源允许重新申请
                g_stManager.busy_mux = 0;
            } 
        }
        else {                                                          //资源未使用
            HAL_DL_LIST_FOR_EACH_ENTRY(item, &g_stManager.list_mux, ThreadCB_S, list_mux_manager) {
            //    printf("thread id=%d,lock_mux=%d,allow_num=%d,owner_mux=%d\r\n",item->id,item->lock_mux,item->allow_mux, g_stManager.owner_mux->id);
                if (item->lock_mux == 1) {                              //找到申请线程
                    assert_param(item->allow_mux == 0);
                    HAL_ListDelete(&item->list_mux_manager);
                    item->allow_mux = 1;
                    g_stManager.busy_mux = 1;
                    g_stManager.owner_mux = item;
                    break;
                }
            }
        }
    }
}

